<?php

class Event extends EventsAppModel 
{
	var $name = 'Event';	
	Const PUBLISH = 1;
	Const UNPUBLISH = 0;
	
	var $scopes = array(
		'published' => array('Event.status'=>self::PUBLISH)
	);	
	
	var $validate = array(
		'title' => array(
				'rule'=>VALID_NOT_EMPTY,
				'message'=>'Title is mandatory'
		),
		'event_from' => array(
				'event_from_create'=> array(
					'rule'=>array('validateFutureDateTime','event_from'),
					'on' => 'create',
					'message'=>'Should be a future date time'
				),
				'validDateTime'=> array(
						'rule'=>array("validateDatetime",'event_from'),
						'message'=>'Enter valid date time'
				)
		),
		'event_to' => array(
				'checkWithDate'=>array(
					'rule'=>array('compareFromTo','event_from','event_to'),
					'message'=> 'Should be a future date time for "When"'
				),
				'validDateTime'=> array(
						'rule'=>array("validateDatetime",'event_to'),
						'message'=>'Enter valid date time'
				)
		),
		'event_cost' => array(
				'rule'=>'numeric',
				'message'=>'Wrong Cost'
		),
		'event_cost_to' => array(
			'event_cost_to_numeric'=> array(
				'rule'=>'numeric',
				'message'=>'Wrong Cost',
				'allowEmpty'=>true
			),
			'event_cost_to_lt_cost' => array(
				'rule'=>array('validateCost','event_cost','event_cost_to'),
				'message'=>'Wrong Cost',
				'allowEmpty'=>true
			)
		),
		'event_site'=>array(
			'event_site_url'=>array(
				'rule'=>'url',
				'message'=>'Wrong URL',
				'allowEmpty'=>true
			)
		),
		'ticket_site'=>array(
			'ticket_site_url'=>array(
				'rule'=>'url',
				'message'=>'Wrong URL',
				'allowEmpty'=>true
			)
		),
		'event_category_id' => array(
			'catmandatory'=>array(
					'rule'=>VALID_NOT_EMPTY,
					'message'=>'Category is mandatory'
			)
		)	
	);

	var $belongsTo = array(
		'User' => array(
			'className' => 'Users.User',
			'foreignKey' => 'user_id',
			'counterCache'=>true,
			'counterScope'=>array('Event.status'=>self::PUBLISH),
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'EventCategory' => array(
			'className' => 'Events.EventCategory',
			'foreignKey' => 'event_category_id',
			'counterCache'=>true,
			'counterScope'=>array('Event.status'=>self::PUBLISH),
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);

	var $hasMany = array(
		'EventAsset' => array(
			'className' => 'Events.EventAsset',
			'foreignKey' => 'event_id',
			'dependent' => true
		),
		'EventAttendee' => array(
			'className' => 'Events.EventAttendee',
			'foreignKey' => 'event_id',
			'dependent' => true
		),
		'EventComment' => array(
			'className' => 'Events.EventComment',
			'foreignKey' => 'event_id',
			'dependent' => true
		),
		'EventInterest' => array(
			'className' => 'Events.EventInterest',
			'foreignKey' => 'event_id',
			'dependent' => true
		),
		'EventSubscriber' => array(
			'className' => 'Events.EventSubscriber',
			'foreignKey' => 'event_id',
			'dependent' => true
		)
	);

	var $actsAs = array(
		'Assets.MultiUpload' => array(
			"type"=>"hasMany",
			"uploadModelName"=>"Events.EventAsset"
		),
			//'Feature'=>array('limit'=>null),
		'Users.UserContent' => array(
			'badwordFilter' => true, 
			'fieldsToFilter' => array('title','description'),
			'posterModels'=>array('Users.User'=>array('dependent'=>true))	
		),
		'Cms.Sluggable'=>array('overwrite'=>true),
		'Containable',
		'Cms.Metric' => array(
			array('metric' => 'NumRecords')
		),
		'Tags.Taggable'=>array(
			'deleteExisting'=>true
		)
	);
	
	var $fieldProperties = array(
			'listing_id'=>array(
					//'group'=>array('add','edit','view'),
					'type'=>'hidden'
			),
			'listing_text'=>array(
					'label'=>'Listing',
					//'group'=>array('add','edit'),
					'type'=>'hidden'
			),
			'event_category_id'=>array(
					'label'=>'Category',
					'group'=>array('add','edit','view'),
					'type'=>'select',
					//'options' => array()
					//'separator'=>'</li><li style=\'float: left; width: 50%;\'>', //for radio buttons
					//'style'=>'border: 1px solid #CCC; margin-top: 30px; padding: 16px 20px;'
			),
			'title'=>array(
					'label'=>'Title',
					'group'=>array('add','edit','view'),
					'type'=>"text",
					'style'=>'text-transform:capitalize;'
					//'onBlur'=>'this.value = this.value.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});'
			),
			'event_from'=>array(
					'label'=>'When',
					'group'=>array('add','edit','view'),
					'type' => "datetime"
			),
			'event_to'=>array(
					'label'=>'Up-to',
					'group'=>array('add','edit','view'),
					'type'=>"datetime",
			),
			/*
			'venue'=>array(
					'label'=>'Where',
					'group'=>array('add','edit','view'),
					'type'=>"textarea",
					'style'=>'text-transform:capitalize;'
			),
			*/
			'status'=>array(
					'group'=>array('add','edit'),
					'type'=>'hidden',
					'options'=>array('0','1'),									
			),
			'description'=>array(
					'label'=>'What/Why',
					'type'=>'textarea',
					'group'=>array('add','edit','view')
			),
			'asset_inputs' => array(
				'type'=>"parent",
				'childInfo' => array(
					'model'=>"Events.EventAsset",
					'allowEdit' => false,
					'child_group' => "add",
					'allowMultiple' => true,
					'deleteMissing' => false,
				),
				'fieldset' => false
			),
			'event_site' => array(
				'label'=>'How (Event Site)',
				'type'=>"text",
				'group'=>array('add','edit','view'),
				//'class'=>'required',
				'style'=>'text-transform:lowercase;'
			),
			'ticket_site' => array(
				'label'=>'How (Ticket Site)',
				'type'=>"text",
				'group'=>array('add','edit','view'),
				//'class'=>'required',
				'style'=>'text-transform:lowercase;'
			),
			'event_cost' => array(
				//'label'=>array('text'=>'Price','style'=>'display: inline;'),
				'label'=>'Price',
				'between'=>'$',
				'type'=>"text",
				'default'=>0,
				'group'=>array('add','edit','view'),
				'style'=>'width: 70%; 	display: inline; 	float: none; clear: none;',
				//'div'=>array('style'=>'display: inline; padding: 5px 5px;')
			),
			'event_cost_to' => array(
				//'label'=>array('text'=>'To','style'=>'display: inline;'),
				'label'=>'To',
				'between'=>'$',
				'type'=>"text",
				'default'=>0,
				'group'=>array('add','edit','view'),
				'style'=>'width: 70%; 	display: inline; 	float: none; clear: none;',
				//'div'=>array('style'=>'display: inline; padding: 5px 5px;')						
			),
			'is_free' => array(
				//'label'=>array('text'=>'Free','style'=>'display: inline;'),
				'label'=>'Free Event',
				'type'=>"checkbox",
				'default'=>1,
				'class'=>'event_free_checkbox',
				//'div'=>array('style'=>'display: inline; padding: 5px 5px;'),
				'group'=>array('add','edit','view'),
				'onclick'=>'if(this.checked){
					document.getElementById(\'EventEventCost\').value=0;
					document.getElementById(\'EventEventCostTo\').value=0;
					document.getElementById(\'EventEventCost\').disabled=true;
					document.getElementById(\'EventEventCostTo\').disabled=true;
					}else{
					document.getElementById(\'EventEventCost\').disabled=false;
					document.getElementById(\'EventEventCostTo\').disabled=false;
					}'
			)			
	);
	
		
		var $additionalFields = array (
			'uploadedFile',
			'image',
			'viewUrl',
			'viewUrlAdmin',
			//'interestedCount'
			'venue',
		);
		var $categoryId = null;
		var $cachedFieldProperties = array();
		
		function checkListingValue($params)
		{
			$result = true;
			if(isset($this->data[$this->alias]['listing_id']) && isset($this->data[$this->alias]['listing_text']))
			{
				if(!$this->data[$this->alias]['listing_id'] || !trim($this->data[$this->alias]['listing_text']))
				{
					$result = false;
				}
			}
			return $result;
		}
		
		function viewUrl($result)
		{
			$url = '/events/events/view/'.$result[$this->alias]['slug'];
			return $url;
		}
		
		function viewUrlAdmin($result)
		{
			$url = '/admin/events/events/view/'.$result[$this->alias]['slug'];
			return $url;
		}
		
		/*function interestedCount($result)
		{
			$iCnt = $result[$this->alias]['whosin_count']+$result[$this->alias]['soundscool_count'];
			return $iCnt;
		}*/
		
		function image($result)
		{
			$image = '/uploads/event_image.gif';
			$useDefault = false;
			if(!empty($result)  &&  isset($result[$this->alias]['uploadedFile']) && !empty($result[$this->alias]['uploadedFile']))
			{
				if($useDefault == false)
				{
					$image = '/uploads/event_assets/'.$result[$this->alias]['uploadedFile'];
				}
			}
			return $image;
		}
	

		function compareFromTo($params,$fromdate,$todate)
		{
			$datefrom = strtotime($this->data[$this->alias][$fromdate]);
			$dateto = strtotime($this->data[$this->alias][$todate]);
			if($dateto > $datefrom)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

	/*
	function validateFutureDate($fieldName, $params)
	{
		if ($result = $this->validateDate($fieldName, $params))
		{
			return $result;
		}
		$date = strtotime($this->data[$this->alias][$params]);

		return $this->_evaluate($date > time(), "is not set in a future date", $fieldName, $params);
	}
	*/

	function validateCost($params)
	{
		if ($params['event_cost_to'] == null || $params['event_cost_to'] == 0)
		{
			return true;
		}
		else 
		{
			$cost = $this->data[$this->alias]['event_cost'];
			$costTo = $params['event_cost_to'];
			if ((float)$cost == 0.0 && ((float)$costTo > (float)$cost)) {
				return false;
			}
			if((float)$cost >= (float)$costTo){
				return false; 
			}else{
				return true;
			}
		}
	}
	/*
	function validateDateTimePassed($fieldName, $params)
	{
		if(false)
		{//change this to compare old value with updated value
			if ($result = $this->validateDate($fieldName, $params))
			{
				return $result;
			}
			$date = strtotime($this->data[$this->alias][$params]);

			return $this->_evaluate($date > time(), "is not set in a future date", $fieldName, $params);
		}
		else
		{
			return true;
		}
	}
	*/
	
	function validateFutureDateTime($params, $fieldName)
	{
		if ($this->validateDatetime($params, $fieldName) == false)
		{   
			return false;
		}
		$date = strtotime($params[$fieldName]);
		if($date > time())
		{
			return true;
		}
		else
		{
			return false;
		}
		
	}
	/*
	function validateDate($fieldName, $params)
	{
		$date = $this->data[$this->alias][$params];
		$datePattern = '/^\d{4}-\d?\d-\d?\d$/';
		$result = true;
		if ($date && preg_match($datePattern, $date))
		{
			$date = explode('-',$date);
			$result = checkdate($date[1], $date[2], $date[0]);
		}
		else
		{
			$result = false;
		}
		
		return $result;
	}
	*/
	
	function validateDatetime($params, $fieldName)
	{
		$result = false;
		$dateTime = $params[$fieldName];
		$dateTimePattern = '/^\d{4}-\d?\d-\d?\d ' . '([01]?[0-9]|[2][0-4]):([0-5]?[0-9]):([0-5]?[0-9])$/'; 
		if ($dateTime && preg_match($dateTimePattern, $dateTime))
		{
			list($date, $time) = explode(' ', $dateTime);
			$date = explode('-',$date);
			$result = checkdate($date[1], $date[2], $date[0]);
		}
		return $result;
	}
	
	function afterInitialize()
	{
		$this->setFieldProperties('asset_inputs', array('addMoreLabel'=>__("Add more Images"),'label'=>__("Images"),));
		parent::afterInitialize();
		$this->cacheFields['uploadedFile'] = "onUpdate";
	}
	
	function hasDefaultImage($id)
	{
		return $this->EventAsset->hasAny(array('is_default'=>1,'event_id'=>$id, 'status'=>EventAsset::PUBLISHED));
	}
	
	function unpublishAssociatedEntity($idsToUpdate = null,$foreignKey = null)
	{
		if(!empty($foreignKey))
		{
			$idsToUpdate = $this->find('list',array('fields'=>array('id'),'conditions'=>array($this->alias.'.'.$foreignKey=>$idsToUpdate)));
			$this->updateAll(array($this->alias.'.status'=>self::UNPUBLISHED),array($this->alias.'.id'=>$idsToUpdate));
		}
		$this->refershCounters($idsToUpdate);

		$belongsToAssociations = $this->belongsTo;
		if(!empty($belongsToAssociations))
		{
			foreach($belongsToAssociations as $parentModel=>$assoc)
			{
				$foreignKey = $assoc['foreignKey'];
				$keys[$foreignKey] = $this->field($foreignKey,array($this->alias.'.id'=>$idsToUpdate));
				$this->updateCounterCache($keys);
			}
		}

		$hasManyAssociations = $this->hasMany;
		if(!empty($hasManyAssociations))
		{
			foreach($hasManyAssociations as $childModel=>$config)
			{
				if(method_exists($this->{$childModel},'unpublishAssociatedEntity'))
				{
					$this->{$childModel}->unpublishAssociatedEntity($idsToUpdate,$config['foreignKey']);
				}
			}
		}
	}
	
	function getDefaultFields()
	{
		$classVars = get_class_vars(__CLASS__);
		$fields =  array_keys($classVars['fieldProperties']);
		$fields = array_combine($fields,$fields);
		unset($fields['asset_inputs']);
		return array_values($fields);
	}
	
	function beforeSave($options = array())
	{
		$result = parent::beforeSave($options);
		if($this->_isNew() || (!isset($this->data[$this->alias]['id']) || !$this->data[$this->alias]['id']))
		{
			$this->data[$this->alias]['is_popular'] = 0;
			$this->data[$this->alias]['popularize_date'] = null;
			$this->data[$this->alias]['comment_count'] = 0;
			$this->data[$this->alias]['views_count'] = 0;
			$this->data[$this->alias]['whosin_count'] = 0;
			$this->data[$this->alias]['soundscool_count'] = 0;
			$this->data[$this->alias]['interested_count'] = 0;
		}
		return $result;
	}
	
	function venue($result)
	{
		$address = "";
		if(isset($result[$this->alias]['listing_id']) && $result[$this->alias]['listing_id'])
		{
			$address = $this->getListingAddress($result[$this->alias]['listing_id']);
		}
		return $address;
	}
	
	function getListingAddress($listingId)
	{
		$address = "";
		$listing = null;
		if(is_array($listingId) && isset($listingId["Listing"]["id"]) && $listingId["Listing"]["id"])
		{
			$listing = $listingId;
			$listingId = $listing["Listing"]["id"];
		} else {
			$listing = cri("Listing")->find('first',array('conditions'=>array("Listing.id"=>$listingId),'recursive'=>-1));
		}
		if($listingId && !empty($listing))
		{
			$fields = array('address1_field','address2_field','city_field','state_field','country_field');
			foreach($fields as $field)
			{
				$listingFieldname = cr("MapConfig.".$field);
				if($listingFieldname && isset($listing['Listing'][$listingFieldname]))
				{
					if(strlen($address))
					{
						$address .= ', ';
					}
					$address .= $listing['Listing'][$listingFieldname];
				}
			}
		}
		return $address;
	}
	
	/**
	 * method to append address (venue), lat, lng information, fetched from the listing attached with the event.
	 */
	function appendLocationInformation($events)
	{
		if(!$events || empty($events) || !is_array($events))
		{
			return $events;
		}
		$singleEventFlag = false;
		if(isset($events[$this->alias]['id']) && $events[$this->alias]['id'])
		{
			$singleEventFlag = true;
			$events = array($events);
		}
		$listingIds = Set::extract("{n}.Event.listing_id", $events);
		$listingIds = array_unique($listingIds);
		$listings = cri("Listing")->find("all",array("conditions"=>array("Listing.id"=>$listingIds),"recursive"=>-1));
		$listings = Set::combine($listings, "{n}.Listing.id","{n}");
		foreach($events as $key=>$event)
		{
			//$event[$this->alias]['venue'] = null;
			$event[$this->alias]['lat'] = null;
			$event[$this->alias]['lng'] = null;
			if(isset($event[$this->alias]['listing_id']) && $event[$this->alias]['listing_id'] && array_key_exists($event[$this->alias]['listing_id'], $listings))
			{
				//$event[$this->alias]['venue'] = $this->getListingAddress($event[$this->alias]['listing_id']);
				$event[$this->alias]['lat'] = $listings[$event[$this->alias]['listing_id']]["Listing"]["lat"];
				$event[$this->alias]['lng'] = $listings[$event[$this->alias]['listing_id']]["Listing"]["lng"];
			}
			$events[$key] = $event;
		}
		return (($singleEventFlag === false)?$events:$events[0]);
	}
	
	//for module data
	function getRecentEvents($limit=3)
	{
		$conditions = array($this->alias.'.status'=>self::PUBLISH);
		$order = array($this->alias.".created" => "desc");
		$recursive = 0;
		$events = $this->find('all',compact('conditions','recursive','order','limit'));
		return $events;
	}
	
	//for module data
	function getPopularThisWeek($limit=3)
	{
		$this->setScope('published');
		$weekStartDate = date('Y-m-d',strtotime('Last Monday', time()));
		$weekEndDate = date('Y-m-d',strtotime('Next Sunday', time()));
		if (date('l') == 'Monday')
		{
			$weekStartDate = date('Y-m-d');
		}
		//weekStartDate is set to the current date as on yelp i see that if a week start from 11th and ends on 17th and current date is 14th then events completed before 14th will not be listed
		$weekStartDate = date('Y-m-d');
		if (date('l') == 'Sunday')
		{
			$weekEndDate = date('Y-m-d');
		}
	
		$conditions = $this->getSeeByDateCondition("This_Week", $weekStartDate, $weekEndDate);
			
		//$order = array($this->alias.".created" => "desc");
		$order = array("Event.interested_count" => "DESC");
		$recursive = 0;
		$events = $this->find('all',compact('conditions','recursive','order','limit'));
		return $events;
	}
	
	//for module data
	function getOtherPopularEvents($limit=3)
	{
		$this->setScope('published');
		$conditions = $this->getOtherPopularEventsCondition();
		//$order = array("(".$this->alias.".soundscool_count + ".$this->alias.".whosin_count)" => "DESC");
		$order = array("Event.interested_count" => "DESC");
		$recursive = 0;
		$events = $this->find('all',compact('conditions','recursive','order','limit'));
		return $events;
	}
	
	function getUpcomingEventsCondition()
	{
		$weekStartDate = date('Y-m-d');
		$weekEndDate = date('Y-m-d',strtotime('Next Sunday', time()));
		if (date('l') == 'Sunday')
		{
			$weekEndDate = date('Y-m-d');
		}
		$conditions = $this->getSeeByDateCondition("This_Week", $weekStartDate, $weekEndDate);
		return $conditions;
	}
	
	function getOtherPopularEventsCondition()
	{
		$weekStartDate = date('Y-m-d',strtotime('Last Monday', time()));
		$weekEndDate = date('Y-m-d',strtotime('Next Sunday', time()));
		if (date('l') == 'Monday')
		{
			$weekStartDate = date('Y-m-d');
		}
		if (date('l') == 'Sunday')
		{
			$weekEndDate = date('Y-m-d');
		}
		$conditions = array("Date(".$this->alias.".event_from) >"=>$weekEndDate);
		/*
		$conditions = array(
			"OR" => array(
				array("Date(".$this->alias.".event_from) >"=>$weekEndDate),
				array("Date(".$this->alias.".event_to) <"=>$weekStartDate)
			)
		);
		*/
		return $conditions;
	}
	
	function getSeeByDateCondition($viewBy = null, $customStartDate = false, $customEndDate = false)
	{
		$conditions = null;
		if ($viewBy)
		{
			$startDate = date('Y-m-d');
			$endDate = date('Y-m-d');
			switch($viewBy) 
			{
				case "All":
					$startDate = date('Y-m-d');
					$endDate = date('Y-m-d');
					break;
				case "Today":
					$startDate = date('Y-m-d');
					$endDate = date('Y-m-d');
					break;
				case "Tomorrow":
					$startDate = date('Y-m-d',strtotime('+1 day', time()));
					$endDate = date('Y-m-d',strtotime('+1 day', time()));
				break;
				case "This_Weekend":
					$startDate = date('Y-m-d',strtotime('Next Friday', time()));
					$endDate = date('Y-m-d',strtotime('Next Sunday', time()));
					if (date('l') == 'Friday')
					{
						$startDate = date('Y-m-d');
					}
					if (date('l') == 'Sunday')
					{
						$startDate = date('Y-m-d');
						$endDate = date('Y-m-d');
					}
				break;
				case "This_Week":
					$startDate = date('Y-m-d',strtotime('Last Monday', time()));
					$endDate = date('Y-m-d',strtotime('Next Sunday', time()));
					if (date('l') == 'Monday')
					{
						$startDate = date('Y-m-d');
					}
					if (date('l') == 'Sunday')
					{
						$endDate = date('Y-m-d');
					}
				break;
				case "Next_Week":
					$startDate = date('Y-m-d',strtotime('Next Monday', time()));
					if (date('l') == 'Sunday')
					{
						$endDate = date('Y-m-d',strtotime('Next Sunday', time()));
					}
					else 
					{
						$endDate = date('Y-m-d',strtotime('Next Sunday',strtotime('+1 week', time())));
					}
				break;
				case "Week_After_Next":
					$startDate = date('Y-m-d',strtotime('Next Monday', strtotime('+1 week', time())));
					if (date('l') == 'Sunday')
					{
						$endDate = date('Y-m-d',strtotime('Next Sunday',strtotime('+1 week', time())));
					}
					else 
					{
						$endDate = date('Y-m-d',strtotime('Next Sunday',strtotime('+2 week', time())));
					}
				break;
				case "Past":
					$startDate = date('Y-m-d');
					$endDate = date('Y-m-d');
				break;
				default:
					$startDate = $viewBy;
					$endDate = $viewBy;
			};
			
			if($customStartDate !== false)
			{
				$startDate = $customStartDate;
			}
			if($customEndDate !== false)
			{
				$endDate = $customEndDate;
			}
			
			if ($viewBy == "All")
			{
				$conditions = "1 = 1";
			} else if ($viewBy == "Past") {
				$conditions = array(
						"AND"=>array(
								array("Date(Event.event_from) <"=>$startDate),
								array("Date(Event.event_to) <"=>$endDate)
						)
				);
			} else {
				$conditions = array(
						"OR" => array(
								array(
										"AND"=>array(
												array("Date(Event.event_from) >="=>$startDate),
												array("Date(Event.event_from) <="=>$endDate)
										)
								),
								array(
										"AND"=>array(
												array("Date(Event.event_to) >="=>$startDate),
												array("Date(Event.event_to) <="=>$endDate)
										)
								),
								array(
										"AND"=>array(
												array("Date(Event.event_from) <"=>$startDate),
												array("Date(Event.event_to) >"=>$endDate)
										)
								)
						)
				);
			}
		}
		return $conditions;
	}
	
	function hasActiveEventsLimitCrossed($listingId)
	{
		$result = false;
		if($listingId && AppUtility::allowPaidListing())
		{
			$EffectivePlan = cri("PaidListings.ListingPlan")->getEffectivePlan($listingId);
			if($EffectivePlan->isEventLimitApplied())
			{
				$totalAllowedEvents = $EffectivePlan->getAllowedActiveEventsCount();
				if(is_null($totalAllowedEvents))
				{
					return false;
				}
				$this->setScope('published');
				$totalActiveEvents = $this->find("count",array("conditions"=>array($this->alias.".listing_id"=>$listingId),"recursive"=>-1));
				if($totalActiveEvents >= $totalAllowedEvents)
				{
					$result = true;
				}
			}
		}
		return $result;
	}
	
	function setListingFieldProperties($listingId)
	{
		$ListingModel = cri("Listing");
		$ListingModel->setScope('published');
		$listing = $ListingModel->find("first",array("conditions"=>array("Listing.id"=>$listingId),"recursive"=>-1));
		if($listingId && !empty($listing))
		{
			$this->setFieldProperties('listing_id', array('group' => array('no_group')));
			$this->setFieldProperties('listing_text', array('group' => array('no_group'), 'validate'=>null));
			//unset($this->fieldProperties['listing_id']);
			//unset($this->fieldProperties['listing_text']);
		} else {
			$this->setFieldProperties('listing_id',array('group'=>array('add','edit','view')));
			$this->setFieldProperties('listing_text',array(
					'type'=>'text',
					'group'=>array('add','edit'),
			));
			$this->validate['listing_text'] = array(
					'notEmpty'=>array(
							'rule'=>VALID_NOT_EMPTY,
							'message'=>'This field is required',
							'required' => true,
							'allowEmpty' => false
					),
					'notSelected'=>array(
							'rule'=>array('checkListingValue'),
							'message'=>'Invalid selection',
							'required' => false,
							'allowEmpty' => true
					)
			);
		}
	}
	
	function getEventsForNewsletter($limit = 10)
	{
		return $this->getRecentEvents($limit);
	}
	
}
?>